import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'package:qilo/core/constants/app_icons.dart';
import 'package:video_player/video_player.dart';
import 'package:chewie/chewie.dart';
import 'package:like_button/like_button.dart';
import 'package:path_provider/path_provider.dart';
import '../../../core/constants/app_colors.dart';

import '../../../core/models/hot_item.dart';
import '../../../core/models/user_model.dart';
import '../../../core/models/comment.dart';
import '../../../core/providers/hot_item_provider.dart';
import '../../../core/providers/global_state_coordinator.dart';
import '../../../core/utils/app_utils.dart';
import '../../../core/utils/image_utils.dart';
import '../../../core/routes/app_router.dart';
import '../../../core/widgets/transgression_reporting_portal.dart';

/// 社区详情页面
class CommunityDetailPage extends StatefulWidget {
  final HotItem item;

  const CommunityDetailPage({super.key, required this.item});

  @override
  State<CommunityDetailPage> createState() => _CommunityDetailPageState();
}

class _CommunityDetailPageState extends State<CommunityDetailPage> {
  VideoPlayerController? _videoPlayerController;
  ChewieController? _chewieController;
  bool _isVideoInitialized = false;
  bool _isLoading = false;
  final TextEditingController _commentController = TextEditingController();

  @override
  void initState() {
    super.initState();
    if (widget.item.isVideo) {
      _initializeVideoPlayer();
    }
  }

  @override
  void dispose() {
    _chewieController?.dispose();
    _videoPlayerController?.dispose();
    _commentController.dispose();
    super.dispose();
  }

  /// 根据发布者ID获取用户信息
  UserModel? _getPublisherInfo() {
    final coordinator = context.read<GlobalStateCoordinator>();
    return coordinator.getDefaultUserById(widget.item.publisherId);
  }

  /// 初始化视频播放器
  Future<void> _initializeVideoPlayer() async {
    if (!widget.item.isVideo) return;

    setState(() {
      _isLoading = true;
    });

    try {
      // 根据资源路径类型创建不同的 VideoPlayerController
      _videoPlayerController = await _createVideoPlayerController(
        widget.item.resourceUrl,
      );

      await _videoPlayerController!.initialize();

      _chewieController = ChewieController(
        videoPlayerController: _videoPlayerController!,
        autoPlay: false,
        looping: false,
        aspectRatio: 16 / 9,
        allowFullScreen: true,
        allowMuting: true,
        showControls: true,
        materialProgressColors: ChewieProgressColors(
          playedColor: AppColors.iconColor,
          handleColor: AppColors.iconColor,
          backgroundColor: Colors.grey.withValues(alpha: 0.3),
          bufferedColor: AppColors.iconColor.withValues(alpha: 0.3),
        ),
        placeholder:
            widget.item.thumbnailUrl != null
                ? Container(
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: _getImageProvider(widget.item.thumbnailUrl!),
                      fit: BoxFit.cover,
                    ),
                  ),
                )
                : null,
      );

      setState(() {
        _isVideoInitialized = true;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      debugPrint('Error initializing video: $e');
    }
  }

  Future<VideoPlayerController> _createVideoPlayerController(
    String resourceUrl,
  ) async {
    if (resourceUrl.startsWith('http://') ||
        resourceUrl.startsWith('https://')) {
      return VideoPlayerController.networkUrl(Uri.parse(resourceUrl));
    }

    if (resourceUrl.startsWith('assets/')) {
      return VideoPlayerController.asset(resourceUrl);
    }

    if (resourceUrl.startsWith('/')) {
      final file = File(resourceUrl);
      if (await file.exists()) {
        return VideoPlayerController.file(file);
      }
    }

    try {
      final appDocDir = await getApplicationDocumentsDirectory();
      final localFile = File('${appDocDir.path}/$resourceUrl');
      if (await localFile.exists()) {
        return VideoPlayerController.file(localFile);
      }
    } catch (e) {
      debugPrint('Error accessing app documents directory: $e');
    }

    try {
      final tempDir = await getTemporaryDirectory();
      final tempFile = File('${tempDir.path}/$resourceUrl');
      if (await tempFile.exists()) {
        return VideoPlayerController.file(tempFile);
      }
    } catch (e) {
      debugPrint('Error accessing temp directory: $e');
    }

    return VideoPlayerController.asset(resourceUrl);
  }

  ImageProvider _getImageProvider(String imagePath) {
    if (imagePath.startsWith('http://') || imagePath.startsWith('https://')) {
      return NetworkImage(imagePath);
    }

    if (imagePath.startsWith('assets/')) {
      return AssetImage(imagePath);
    }

    final file = File(imagePath);
    if (file.existsSync()) {
      return FileImage(file);
    }

    return AssetImage(imagePath);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/my-bg.png'),
          fit: BoxFit.cover,
        ),
      ),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: SafeArea(
          bottom: false,
          child: Stack(
            children: [
              Column(
                children: [
                  _buildHeader(),
                  Expanded(
                    child: SingleChildScrollView(
                      padding: EdgeInsets.only(bottom: 60.h),
                      child: Column(
                        children: [
                          _buildResourceSection(),
                          _buildCommentsSection(),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
              Positioned(
                left: 0,
                right: 0,
                bottom: 0,
                child: _buildFixedCommentInput(),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildHeader() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          GestureDetector(
            onTap: () => Navigator.pop(context),
            child: Container(
              width: 30.w,
              height: 30.w,
              decoration: BoxDecoration(
                color: Colors.transparent,
                shape: BoxShape.circle,
              ),
              child: Icon(
                Icons.arrow_back_ios_new,
                color: Colors.white,
                size: 24.sp,
              ),
            ),
          ),
          Text(
            'Circle',
            style: TextStyle(
              color: Colors.white,
              fontSize: 22.sp,
              fontFamily: 'Poppins',
              fontWeight: FontWeight.w400,
            ),
          ),
          GestureDetector(
            onTap: _handleReport,
            child: Container(
              width: 30.w,
              height: 30.w,
              decoration: BoxDecoration(
                color: Colors.transparent,
                shape: BoxShape.circle,
              ),
              child: Icon(MyIcons.iconReport, color: Colors.white, size: 24.sp),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildResourceSection() {
    return Column(
      children: [
        _buildPublishInfo(),
        _buildMediaContent(),
        Container(
          margin: EdgeInsets.symmetric(horizontal: 16.w),
          child: _buildInteractionContent(),
        ),
      ],
    );
  }

  Widget _buildMediaContent() {
    return Container(
      decoration: const BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/detail-card-bg.png'),
          fit: BoxFit.contain,
        ),
      ),
      margin: EdgeInsets.only(left: 10.w, right: 10.w),
      child: Padding(
        padding: EdgeInsets.only(
          top: 46.h,
          bottom: 56.h,
          left: 36.w,
          right: 36.w,
        ),
        child: ClipRRect(
          child: AspectRatio(
            aspectRatio: 292 / 327,
            child:
                widget.item.isVideo
                    ? _buildVideoPlayer()
                    : _buildImageDisplay(),
          ),
        ),
      ),
    );
  }

  Widget _buildPublishInfo() {
    final publisherInfo = _getPublisherInfo();
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 26.w),
      child: Row(
        children: [
          GestureDetector(
            onTap: () => _navigateToUserProfile(),
            child: Container(
              width: 40.w,
              height: 40.w,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: publisherInfo == null ? AppColors.iconColor : null,
                image:
                    publisherInfo?.avatar.isNotEmpty == true
                        ? DecorationImage(
                          image: ImageUtils.getImageProvider(
                            publisherInfo!.avatar,
                          ),
                          fit: BoxFit.cover,
                        )
                        : null,
              ),
              child:
                  publisherInfo?.avatar.isEmpty != false
                      ? Text(
                        (publisherInfo?.userName ?? widget.item.publisherId)
                            .substring(0, 1)
                            .toUpperCase(),
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 16.sp,
                          fontWeight: FontWeight.bold,
                        ),
                      )
                      : null,
            ),
          ),
          SizedBox(width: 12.w),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                GestureDetector(
                  onTap: () => _navigateToUserProfile(),
                  child: Text(
                    publisherInfo?.userName ?? widget.item.publisherId,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 16.sp,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ),
                Text(
                  widget.item.title,
                  style: TextStyle(
                    color: Colors.white.withValues(alpha: 0.8),
                    fontSize: 14.sp,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建视频播放器
  Widget _buildVideoPlayer() {
    if (_isLoading) {
      return Container(
        color: Colors.black,
        child: const Center(
          child: CircularProgressIndicator(color: AppColors.iconColor),
        ),
      );
    }

    if (_isVideoInitialized && _chewieController != null) {
      return Chewie(controller: _chewieController!);
    }

    return Container(
      color: Colors.black,
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.error_outline, color: Colors.white, size: 48.sp),
            SizedBox(height: 16.h),
            Text(
              'Video loading failed',
              style: TextStyle(color: Colors.white, fontSize: 16.sp),
            ),
            SizedBox(height: 16.h),
            GestureDetector(
              onTap: _initializeVideoPlayer,
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 24.w, vertical: 12.h),
                decoration: BoxDecoration(
                  color: AppColors.iconColor,
                  borderRadius: BorderRadius.circular(20.r),
                ),
                child: Text(
                  'Retry',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildImageDisplay() {
    return Container(
      decoration: BoxDecoration(
        image: DecorationImage(
          image: _getImageProvider(widget.item.resourceUrl),
          fit: BoxFit.cover,
        ),
      ),
      child:
          widget.item.isVideo
              ? Center(
                child: Container(
                  width: 60.w,
                  height: 60.w,
                  decoration: BoxDecoration(
                    color: Colors.black.withValues(alpha: 0.6),
                    shape: BoxShape.circle,
                  ),
                  child: Icon(
                    Icons.play_arrow,
                    color: Colors.white,
                    size: 30.sp,
                  ),
                ),
              )
              : null,
    );
  }

  Widget _buildInteractionContent() {
    return Container(
      decoration: BoxDecoration(borderRadius: BorderRadius.circular(12.r)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            widget.item.description,
            style: TextStyle(color: Colors.white, fontSize: 14.sp, height: 1.4),
          ),
          SizedBox(height: 16.h),
          Consumer<HotItemProvider>(
            builder: (context, provider, child) {
              final currentItem =
                  provider.getItemById(widget.item.id) ?? widget.item;
              final isLiked = provider.isLiked(widget.item.id);

              return Row(
                children: [
                  _buildInteractionButton(
                    icon: MyIcons.iconComment,
                    count: currentItem.formattedCommentCount,
                    onTap: _handleComment,
                  ),
                  SizedBox(width: 24.w),
                  _buildLikeButton(
                    isLiked: isLiked,
                    likeCount: currentItem.likeCount,
                    onTap:
                        (isLiked) =>
                            _handleLikeWithAnimation(provider, isLiked),
                  ),
                  const Spacer(),
                ],
              );
            },
          ),
          SizedBox(height: 20.h),
          Divider(color: Colors.white.withValues(alpha: 0.5), height: 1.h),
          SizedBox(height: 20.h),
        ],
      ),
    );
  }

  Widget _buildInteractionButton({
    required IconData icon,
    required String count,
    required VoidCallback onTap,
    bool isActive = false,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Row(
        children: [
          Icon(
            icon,
            color: isActive ? AppColors.iconColor : Colors.white,
            size: 24.sp,
          ),
          SizedBox(width: 4.w),
          Text(
            count,
            style: TextStyle(
              color: isActive ? AppColors.iconColor : Colors.white,
              fontSize: 14.sp,
              fontWeight: FontWeight.w500,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildLikeButton({
    required bool isLiked,
    required int likeCount,
    required Future<bool> Function(bool) onTap,
  }) {
    return Row(
      children: [
        LikeButton(
          isLiked: isLiked,
          onTap: onTap,
          size: 24.sp,
          circleColor: const CircleColor(
            start: Color(0xff00ddff),
            end: Color(0xff0099cc),
          ),
          bubblesColor: const BubblesColor(
            dotPrimaryColor: Color(0xff33b5e5),
            dotSecondaryColor: Color(0xff0099cc),
          ),
          likeBuilder: (bool isLiked) {
            return Icon(
              isLiked ? MyIcons.iconCollectFill : MyIcons.iconCollect,
              color: isLiked ? Colors.redAccent : Colors.white,
              size: 24.sp,
            );
          },
        ),
        SizedBox(width: 4.w),
        Text(
          likeCount.toString(),
          style: TextStyle(
            color: Colors.white,
            fontSize: 14.sp,
            fontWeight: FontWeight.w500,
          ),
        ),
      ],
    );
  }

  Widget _buildCommentsSection() {
    return Consumer<HotItemProvider>(
      builder: (context, provider, child) {
        final comments = provider.getCommentsForItem(widget.item.id);

        return Container(
          margin: EdgeInsets.symmetric(horizontal: 16.w),
          decoration: BoxDecoration(borderRadius: BorderRadius.circular(12.r)),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                'Comments',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 16.sp,
                  fontWeight: FontWeight.w600,
                ),
              ),
              SizedBox(height: 16.h),
              if (comments.isEmpty)
                _buildEmptyCommentsPlaceholder()
              else
                ...comments.map(
                  (comment) => Padding(
                    padding: EdgeInsets.only(bottom: 12.h),
                    child: _buildCommentItem(comment: comment),
                  ),
                ),
              SizedBox(height: 100.h),
            ],
          ),
        );
      },
    );
  }

  Widget _buildEmptyCommentsPlaceholder() {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 24.h),
      child: Center(
        child: Text(
          'No comments yet. Be the first to comment!',
          style: TextStyle(
            color: Colors.white.withValues(alpha: 0.6),
            fontSize: 14.sp,
          ),
        ),
      ),
    );
  }

  Widget _buildCommentItem({required Comment comment}) {
    return Consumer2<HotItemProvider, GlobalStateCoordinator>(
      builder: (context, provider, coordinator, child) {
        final userInfo = coordinator.getDefaultUserById(comment.userId);
        final displayName = userInfo?.userName ?? comment.userName;
        final displayAvatar = userInfo?.avatar ?? comment.userAvatar;

        return Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            GestureDetector(
              onTap: () => _navigateToCommentUserProfile(comment.userId),
              child: Container(
                width: 32.w,
                height: 32.w,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: displayAvatar.isEmpty ? AppColors.iconColor : null,
                  image:
                      displayAvatar.isNotEmpty
                          ? DecorationImage(
                            image: ImageUtils.getImageProvider(displayAvatar),
                            fit: BoxFit.cover,
                          )
                          : null,
                ),
                child:
                    displayAvatar.isEmpty
                        ? Center(
                          child: Text(
                            displayName.substring(0, 1).toUpperCase(),
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 12.sp,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        )
                        : null,
              ),
            ),
            SizedBox(width: 12.w),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Text(
                        displayName,
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 14.sp,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                      const Spacer(),
                      GestureDetector(
                        onTap: () => _showCommentOptions(comment),
                        child: Icon(
                          MyIcons.iconReport,
                          color: Colors.white,
                          size: 18.sp,
                        ),
                      ),
                    ],
                  ),
                  SizedBox(height: 4.h),
                  Text(
                    comment.content,
                    style: TextStyle(
                      color: Colors.white.withValues(alpha: 0.9),
                      fontSize: 13.sp,
                      height: 1.3,
                    ),
                  ),
                  SizedBox(height: 8.h),
                  Row(
                    children: [
                      Text(
                        comment.formattedTimeAgo,
                        style: TextStyle(
                          color: Colors.white.withValues(alpha: 0.6),
                          fontSize: 12.sp,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        );
      },
    );
  }

  Widget _buildFixedCommentInput() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      decoration: const BoxDecoration(color: Colors.transparent),
      child: SafeArea(
        top: false,
        child: Row(
          children: [
            Consumer<GlobalStateCoordinator>(
              builder: (context, coordinator, child) {
                final user = coordinator.currentUser;
                return Container(
                  width: 60.w,
                  height: 60.w,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    color: user == null ? AppColors.iconColor : null,
                    image:
                        user?.avatar.isNotEmpty == true
                            ? DecorationImage(
                              image: ImageUtils.getImageProvider(user!.avatar),
                              fit: BoxFit.cover,
                            )
                            : null,
                  ),
                  child:
                      user?.avatar.isEmpty != false
                          ? Center(
                            child: Text(
                              user?.userName.substring(0, 1).toUpperCase() ??
                                  'U',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 12.sp,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          )
                          : null,
                );
              },
            ),
            SizedBox(width: 12.w),
            Expanded(
              child: Container(
                padding: EdgeInsets.only(
                  left: 16.w,
                  top: 8.h,
                  bottom: 8.h,
                  right: 8.w,
                ),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(32.r),
                ),
                child: Row(
                  children: [
                    Expanded(
                      child: TextField(
                        controller: _commentController,
                        style: TextStyle(color: Colors.black, fontSize: 14.sp),
                        decoration: InputDecoration(
                          hintText: 'Say Something',
                          hintStyle: TextStyle(
                            color: Colors.grey,
                            fontSize: 14.sp,
                          ),
                          border: InputBorder.none,
                          contentPadding: EdgeInsets.zero,
                        ),
                        onSubmitted: _submitComment,
                      ),
                    ),
                    GestureDetector(
                      onTap: () => _submitComment(_commentController.text),
                      child: Container(
                        width: 47.w,
                        height: 47.w,
                        decoration: BoxDecoration(
                          color: AppColors.iconColor,
                          shape: BoxShape.circle,
                        ),
                        child: Icon(
                          MyIcons.iconSend,
                          color: Colors.white,
                          size: 22.sp,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future<bool> _handleLikeWithAnimation(
    HotItemProvider provider,
    bool isLiked,
  ) async {
    final coordinator = context.read<GlobalStateCoordinator>();

    if (!coordinator.isLoggedIn) {
      AppUtils.showLoginRequired(
        context,
        message: 'Please login to like this post',
        onLogin: () {
          Navigator.pushNamed(context, '/auth');
        },
      );
      return isLiked;
    }

    provider.toggleLike(widget.item.id);
    return !isLiked;
  }

  void _handleComment() {
    final coordinator = context.read<GlobalStateCoordinator>();

    if (!coordinator.isLoggedIn) {
      AppUtils.showLoginRequired(
        context,
        message: 'Please login to comment on this post',
        onLogin: () {
          Navigator.pushNamed(context, '/auth');
        },
      );
      return;
    }
  }

  void _handleReport() {
    TransgressionReportingPortal.manifestReportingRealm(
      context,
      targetId: widget.item.id,
      targetType: 'community_post',
      onReportSubmitted: (transgression) {
        _deleteHotItemAndGoBack();
      },
    );
  }

  void _deleteHotItemAndGoBack() {
    final hotItemProvider = context.read<HotItemProvider>();
    hotItemProvider.removeItem(widget.item.id);

    Navigator.of(context).pop(true);
  }

  void _submitComment(String comment) {
    final coordinator = context.read<GlobalStateCoordinator>();

    if (!coordinator.isLoggedIn) {
      AppUtils.showLoginRequired(
        context,
        message: 'Please login to comment',
        onLogin: () {
          Navigator.pushNamed(context, '/auth');
        },
      );
      return;
    }

    if (comment.trim().isEmpty) {
      return;
    }

    final currentUser = coordinator.currentUser;
    if (currentUser != null) {
      final provider = context.read<HotItemProvider>();

      provider.addComment(
        itemId: widget.item.id,
        userId: currentUser.id,
        userName: currentUser.userName,
        userAvatar: currentUser.avatar,
        content: comment.trim(),
      );

      _commentController.clear();
      AppUtils.showSuccess(context, 'Comment posted successfully!');
    }
  }

  void _showCommentOptions(Comment comment) {
    TransgressionReportingPortal.manifestReportingRealm(
      context,
      targetId: comment.id,
      targetType: 'comment',
      onReportSubmitted: (transgression) {
        _deleteReportedComment(comment);
      },
    );
  }

  void _deleteReportedComment(Comment comment) {
    final provider = context.read<HotItemProvider>();
    provider.deleteComment(widget.item.id, comment.id);
  }

  void _navigateToCommentUserProfile(String userId) {
    final coordinator = context.read<GlobalStateCoordinator>();
    final currentUser = coordinator.currentUser;

    if (currentUser != null && currentUser.id == userId) {
      return;
    }

    Navigator.pushNamed(context, AppRouter.otherUser, arguments: userId);
  }

  void _navigateToUserProfile() {
    final coordinator = context.read<GlobalStateCoordinator>();
    final currentUser = coordinator.currentUser;

    if (currentUser != null && currentUser.id == widget.item.publisherId) {
      return;
    }

    Navigator.pushNamed(
      context,
      AppRouter.otherUser,
      arguments: widget.item.publisherId,
    );
  }
}
